<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="fragments/header :: head('编辑书籍')">
    <title>编辑书籍 - 校园二手书交易平台</title>
</head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="fragments/header :: navbar('my-books')"></nav>

    <!-- 页面内容 -->
    <div class="container mt-4 page-content">
        <!-- 导航面包屑 -->
        <div th:with="breadcrumbs=${
            {
                {title: '我的书籍', url: '/booktrading/book/my-books'},
                {title: '编辑书籍', url: ''}
            }
        }" th:replace="fragments/header :: breadcrumb(${breadcrumbs})"></div>
        
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="edit-form">
                    <h2 class="edit-title">编辑书籍信息</h2>
                    
                    <!-- 提示信息区域 -->
                    <div id="alertContainer"></div>
                    
                    <form id="editForm">
                        <input type="hidden" id="id" name="id" th:value="${book.id}">
                        
                        <!-- 书籍基本信息 -->
                        <h4 class="mb-3">基本信息</h4>
                        <div class="form-group">
                            <label for="title" class="required-field">书籍标题</label>
                            <input type="text" class="form-control" id="title" name="title" th:value="${book.title}" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="author">作者</label>
                                <input type="text" class="form-control" id="author" name="author" th:value="${book.author}">
                            </div>
                            <div class="form-group col-md-6">
                                <label for="publisher">出版社</label>
                                <input type="text" class="form-control" id="publisher" name="publisher" th:value="${book.publisher}">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="isbn">ISBN</label>
                                <input type="text" class="form-control" id="isbn" name="isbn" th:value="${book.isbn}">
                            </div>
                            <div class="form-group col-md-6">
                                <label for="category">分类</label>
                                <select class="form-control" id="category" name="category">
                                    <option value="教材教辅" th:selected="${book.category == '教材教辅'}">教材教辅</option>
                                    <option value="专业书籍" th:selected="${book.category == '专业书籍'}">专业书籍</option>
                                    <option value="文学小说" th:selected="${book.category == '文学小说'}">文学小说</option>
                                    <option value="考试资料" th:selected="${book.category == '考试资料'}">考试资料</option>
                                    <option value="其他" th:selected="${book.category == '其他'}">其他</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- 价格信息 -->
                        <h4 class="mb-3 mt-4">价格信息</h4>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="originalPrice">原价（元）</label>
                                <input type="number" class="form-control" id="originalPrice" name="originalPrice" step="0.01" min="0" th:value="${book.originalPrice}">
                            </div>
                            <div class="form-group col-md-6">
                                <label for="price" class="required-field">售价（元）</label>
                                <input type="number" class="form-control" id="price" name="price" step="0.01" min="0" th:value="${book.price}" required>
                            </div>
                        </div>
                        
                        <!-- 书籍状况 -->
                        <h4 class="mb-3 mt-4">书籍状况</h4>
                        <div class="form-group">
                            <label for="condition" class="required-field">书籍成色</label>
                            <select class="form-control" id="condition" name="condition" required>
                                <option value="1" th:selected="${book.condition == 1}">全新（未拆封或使用过）</option>
                                <option value="2" th:selected="${book.condition == 2}">优良（几乎全新，无明显痕迹）</option>
                                <option value="3" th:selected="${book.condition == 3}">良好（有使用痕迹，但无缺页、破损）</option>
                                <option value="4" th:selected="${book.condition == 4}">一般（有轻微破损或笔记）</option>
                                <option value="5" th:selected="${book.condition == 5}">较差（有明显破损或大量笔记）</option>
                            </select>
                        </div>
                        
                        <!-- 书籍描述 -->
                        <h4 class="mb-3 mt-4">书籍描述</h4>
                        <div class="form-group">
                            <label for="description">详细描述</label>
                            <textarea class="form-control" id="description" name="description" rows="4" th:text="${book.description}"></textarea>
                            <small class="form-text text-muted">请详细描述书籍的使用情况、是否有笔记、破损等信息</small>
                        </div>
                        
                        <!-- 书籍图片 -->
                        <h4 class="mb-3 mt-4">书籍图片</h4>
                        <div class="form-group">
                            <label for="imageUpload">更换图片</label>
                            <input type="file" class="form-control-file" id="imageUpload" accept="image/*">
                            <small class="form-text text-muted">建议上传清晰的封面照片，大小不超过5MB</small>
                            <input type="hidden" id="imageUrl" name="imageUrl" th:value="${book.imageUrl}">
                            <div id="uploadProgress" class="progress mt-2" style="display: none;">
                                <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                            </div>
                            <div id="imagePreviewContainer" class="mt-2">
                                <img id="imagePreview" class="image-preview lazy-load" th:data-src="${book.imageUrl != null ? book.imageUrl : '/booktrading/static/images/default-book.jpg'}" src="/booktrading/static/images/loading.gif">
                                <button type="button" class="btn btn-sm btn-danger mt-2" id="removeImage">
                                    <i class="fas fa-trash-alt mr-1"></i> 删除图片
                                </button>
                            </div>
                        </div>
                        
                        <!-- 提交按钮 -->
                        <div class="form-group mt-4 text-center">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save mr-1"></i> 保存修改
                            </button>
                            <a th:href="@{'/booktrading/book/detail/' + ${book.id}}" class="btn btn-secondary btn-lg ml-2">
                                <i class="fas fa-times mr-1"></i> 取消
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer th:replace="fragments/footer :: footer"></footer>

    <!-- JavaScript引用 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
    <script th:src="@{/static/js/common.js}"></script>
    
    <!-- 页面特定脚本 -->
    <script th:inline="javascript">
        $(document).ready(function() {
            // 初始化图片预览
            initImagePreview();
            
            // 表单提交处理
            $('#editForm').submit(function(e) {
                e.preventDefault();
                
                // 显示加载指示器
                showLoader();
                
                // 获取表单数据
                var formData = {
                    id: $('#id').val(),
                    title: $('#title').val().trim(),
                    author: $('#author').val().trim(),
                    publisher: $('#publisher').val().trim(),
                    isbn: $('#isbn').val().trim(),
                    category: $('#category').val(),
                    originalPrice: parseFloat($('#originalPrice').val()) || 0,
                    price: parseFloat($('#price').val()) || 0,
                    condition: parseInt($('#condition').val()),
                    description: $('#description').val().trim(),
                    imageUrl: $('#imageUrl').val()
                };
                
                // 表单验证
                if (!validateForm(formData)) {
                    hideLoader();
                    return;
                }
                
                // 发送请求
                $.ajax({
                    url: '/booktrading/book/update',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(response) {
                        hideLoader();
                        if (response.success) {
                            showAlert('success', '保存成功！');
                            setTimeout(function() {
                                window.location.href = '/booktrading/book/my-books';
                            }, 1500);
                        } else {
                            showAlert('danger', response.message || '保存失败，请稍后重试');
                        }
                    },
                    error: function(xhr) {
                        hideLoader();
                        showAlert('danger', '系统错误，请稍后重试');
                    }
                });
            });
            
            // 图片上传处理
            $('#imageUpload').change(function(e) {
                var file = e.target.files[0];
                if (!file) return;
                
                // 验证文件类型和大小
                if (!validateImage(file)) return;
                
                // 显示上传进度条
                $('#uploadProgress').show();
                
                // 创建FormData对象
                var formData = new FormData();
                formData.append('file', file);
                
                // 发送上传请求
                $.ajax({
                    url: '/booktrading/book/upload-image',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    xhr: function() {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                var percent = Math.round((e.loaded / e.total) * 100);
                                $('#uploadProgressBar').css('width', percent + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#imageUrl').val(response.imageUrl);
                            $('#imagePreview').attr('src', response.imageUrl);
                            showAlert('success', '图片上传成功！');
                        } else {
                            showAlert('danger', response.message || '图片上传失败');
                        }
                    },
                    error: function() {
                        showAlert('danger', '图片上传失败，请稍后重试');
                    },
                    complete: function() {
                        $('#uploadProgress').hide();
                        $('#uploadProgressBar').css('width', '0%');
                    }
                });
            });
            
            // 删除图片
            $('#removeImage').click(function() {
                $('#imageUrl').val('');
                $('#imagePreview').attr('src', '/booktrading/static/images/default-book.jpg');
                showAlert('success', '图片已删除');
            });
        });
        
        // 初始化图片预览
        function initImagePreview() {
            var imageUrl = $('#imageUrl').val();
            if (imageUrl) {
                $('#imagePreview').attr('src', imageUrl);
            }
        }
        
        // 表单验证
        function validateForm(data) {
            if (!data.title) {
                showAlert('danger', '请输入书籍标题');
                return false;
            }
            if (data.price <= 0) {
                showAlert('danger', '请输入有效的售价');
                return false;
            }
            if (!data.condition) {
                showAlert('danger', '请选择书籍成色');
                return false;
            }
            return true;
        }
        
        // 图片验证
        function validateImage(file) {
            // 验证文件类型
            if (!file.type.match('image.*')) {
                showAlert('danger', '请选择图片文件');
                return false;
            }
            
            // 验证文件大小（5MB）
            if (file.size > 5 * 1024 * 1024) {
                showAlert('danger', '图片大小不能超过5MB');
                return false;
            }
            
            return true;
        }
        
        // 显示提示信息
        function showAlert(type, message) {
            var alertHtml = '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
                message +
                '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
                '</button>' +
                '</div>';
            $('#alertContainer').html(alertHtml);
            
            // 滚动到提示信息
            $('html, body').animate({
                scrollTop: $('#alertContainer').offset().top - 100
            }, 'fast');
        }
        
        // 显示加载指示器
        function showLoader() {
            $('#page-loader').fadeIn(300);
        }
        
        // 隐藏加载指示器
        function hideLoader() {
            $('#page-loader').fadeOut(300);
        }
    </script>
</body>
</html> 